//
//  ChangePassWordTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/8.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

class ChangePassWordTableViewController: BaseTableViewController {
    
    @IBOutlet weak var codeBtn: UIButton!
    @IBOutlet weak var codeField: UITextField!
    @IBOutlet weak var oldPassWord: UITextField!
    @IBOutlet weak var newPassWord: UITextField!
    @IBOutlet weak var confirmPassWord: UITextField!
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.title = "修改密码"
        self.codeField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.oldPassWord.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.newPassWord.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.confirmPassWord.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        
        
        self.codeField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.oldPassWord.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.newPassWord.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.confirmPassWord.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
    }
    
    @objc func valueChange(textField:UITextField) {
        let maxLength = textField == self.codeField ? 4 : 12
        let toBeString = textField.text!
        let lang = textField.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = textField.markedTextRange
            if selectedRange == nil && toBeString.count > maxLength{
                let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
                textField.text = String(toBeString[..<endIndex])
            }
        }else if toBeString.count > maxLength {
            let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
            textField.text = String(toBeString[..<endIndex])
        }
    }

    // MARK:获取验证码
    @IBAction func getCode(_ sender: UIButton) {
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.get_code.rawValue, parameters: ["username":Utils.getUserDefaulsFor(key: "username") as! String,"type":1]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                self.dispatchTimer(timeInterval: 1, handler: { (count) in
                    self.codeBtn.setTitle("剩余"+"‘\(count)s", for: .normal)
                    sender.isUserInteractionEnabled = false
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
        
    }
    
    func dispatchTimer(timeInterval: Double, handler:@escaping (Int)->()){
        var timeCount = 61
        let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
        codeTimer.schedule(deadline: .now(), repeating: timeInterval)
        codeTimer.setEventHandler(handler: {
            
            timeCount = timeCount - 1
            
            if timeCount <= 0 {
                codeTimer.cancel()
            }
            
            DispatchQueue.main.async {
                if timeCount <= 0 {
                    self.codeBtn.isUserInteractionEnabled = true
                    self.codeBtn.setTitle("获取验证码", for: .normal)
                }else{
                    handler(timeCount)
                }
                
            }
        })
        codeTimer.resume()
    }
    
    
    @IBAction func confirmClick(_ sender: UIButton) {
        if (self.oldPassWord.text?.count)! < 6 {
            PKhud.showText(text: "旧密码错误~")
            self.oldPassWord.becomeFirstResponder()
            return
        }
        
        if (self.newPassWord.text?.count)! < 6 {
            PKhud.showText(text: "密码强度过低，需至少6位~")
            self.newPassWord.becomeFirstResponder()
            return
        }
        
        if self.newPassWord.text != self.confirmPassWord.text {
            PKhud.showText(text: "两次密码不一致，请重新填写~")
            self.confirmPassWord.becomeFirstResponder()
            return
        }
        
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.userUpdatePassword.rawValue, parameters: ["code":self.codeField.text!,"password":self.oldPassWord.text!,"newPassword":self.newPassWord.text!]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                UserDefaults.standard.set(self.newPassWord.text!.MD5String, forKey: "password")
                UserDefaults.standard.synchronize()
                PKhud.showText(text: "密码修改成功，请重新登录~")
                Utils.DispatchAfter(after: 2, handler: {
                    self.backBarButtonMethon()
                })
                
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 4
    }


}
